//
//  BrandsViewController.m
//  SYiDaiy
//
//  Created by dllo on 16/8/26.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "BrandsViewController.h"
#import "TAMacro.h"

#import "AFNetworking.h"



#import "Brandesarray.h"

#import "WikipediaViewController.h"

#import "BrandCustomCollectionViewCell.h"
#import "CustomCollectionReusableView.h"

#import "brandCustomTableViewCell.h"
#import "BrandDetailViewController.h"


#import "Wikipediaesarray.h"

#import "BrandTopViewController.h"

#import "MoreESRootClass.h"
#import "MoreGrids.h"
#import "MoreGoodies.h"
#import "MoreVersion.h"
#import "MoreBanner_Brand.h"
#import "MoreBadge.h"
#import "MoreApps.h"


#import "TAMacro.h"
#import "AFNetworking.h"

#import "BrandESRootClass.h"
#import "Brandesarray.h"

#import "BrandDetailViewController.h"
@interface BrandsViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic,strong) MoreESRootClass *moreESRootClass;
@property (nonatomic,strong) MoreGoodies *moreGoodies;





@property (nonatomic,strong) NSMutableArray *brandTitleArray;
@property (nonatomic,strong) NSMutableArray *headerViewTitleArray;

@property (nonatomic,strong) NSArray *arr;


//腕表百科
@property (nonatomic,strong) NSMutableArray<Wikipediaesarray *> *wikipediaesArray;
@property (nonatomic,strong) UIButton *wikiButton;

//集合视图
@property (nonatomic,strong) UICollectionView *brandCollection;
@property (nonatomic,strong) UICollectionViewFlowLayout *flow;


@property (nonatomic,strong) NSMutableArray<Brandesarray *> *brandArray;
@property (nonatomic,strong) Brandesarray *brandesarray;

@property (nonatomic,strong) NSMutableDictionary *brandMutabDictionary;
@property (nonatomic,strong) NSMutableDictionary *brandLinkShareDictionary;

@property (nonatomic,strong) NSMutableArray *falseIndexArray;
@property (nonatomic,strong) NSMutableArray *indexArray;

@property (nonatomic,strong) NSMutableArray *link_shareArray;



@end

@implementation BrandsViewController

#pragma mark --------试图加载
- (void)viewDidLoad {
    [super viewDidLoad];
    

    self.navigationItem.title = @"WATCHBRANDS";

    
    [self creatCollectionView];
    [self createwikiButton];
}

- (void)createwikiButton
{
    _wikiButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _wikiButton.frame = CGRectMake(0, 0, SCREEN_WIDTH, 50);
    
    [_wikiButton addTarget:self action:@selector(wikipedClicked) forControlEvents:UIControlEventTouchUpInside];
    [_wikiButton setTitle:@"WIKI腕表百科" forState:UIControlStateNormal];
    [_wikiButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _wikiButton.backgroundColor = [UIColor colorWithWhite:0.705 alpha:1.000];
    [self.view addSubview:_wikiButton];
}

- (void)creatCollectionView
{

    _flow = [UICollectionViewFlowLayout new];
//    _flow.sectionHeadersPinToVisibleBounds = YES;
    [_flow setItemSize:CGSizeMake((SCREEN_WIDTH - 15) / 2, 120)];
    [_flow setSectionInset:UIEdgeInsetsMake(5, 5, 5, 5)];
    _flow.minimumInteritemSpacing = 5;
    _flow.minimumLineSpacing = 5;
    
    _flow.sectionHeadersPinToVisibleBounds = YES;
    _brandCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 50, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49 - 50) collectionViewLayout:_flow];


    [self.brandCollection reloadData];
    [self brandNetwork];
    [self wikipediaNetwork];
    
    _brandCollection.backgroundColor = [UIColor colorWithWhite:0.918 alpha:1.000];
    
    _brandCollection.delegate = self;
    _brandCollection.dataSource = self;
    
    _flow.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 30);
    [_brandCollection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"brandCollectionCell"];
    [_brandCollection registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"brandCollectionReuse"];
    [self.view addSubview:_brandCollection];
}

#pragma mark --------集合视图的头视图实现
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reuse = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"brandCollectionReuse" forIndexPath:indexPath];
    reuse.backgroundColor = [UIColor colorWithWhite:0.834 alpha:1.000];
    UILabel *reuseLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 30, 30)];
    [reuse setAlpha:0.5];
    [reuseLabel setTextColor:[UIColor blackColor]];
    [reuseLabel setTextAlignment:1];
    reuseLabel.text = _indexArray[indexPath.section];
    [reuse addSubview:reuseLabel];

    
    return reuse;
}

#pragma mark -------------集合视图的返回cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"brandCollectionCell" forIndexPath:indexPath];

    UIImageView *brandImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, (SCREEN_WIDTH - 15) / 2, 120)];
    
    [brandImageView sd_setImageWithURL:[NSURL URLWithString:[[_brandMutabDictionary objectForKey:[_indexArray objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row]]];
    [cell addSubview:brandImageView];
    

    
    return cell;
}

#pragma mark -------------集合视图的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [[_brandMutabDictionary objectForKey:[_indexArray objectAtIndex:section]] count];
}

#pragma mark -------------集合视图的分区个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _indexArray.count;
}


#pragma mark --------------网络请求
- (void)brandNetwork
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    NSString *requestURLString = @"http://watch-cdn.idailywatch.com/api/list/brands/zh-hans?page=1&ver=iphone&app_ver=15";
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    [session setResponseSerializer:[AFJSONResponseSerializer serializer]];
    [session GET:requestURLString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        _brandArray = [NSMutableArray array];
        _falseIndexArray = [NSMutableArray array];
        _indexArray = [NSMutableArray array];
        NSMutableArray *array = [NSMutableArray array];
        [self setLink_shareArray:array];
        
        for (NSDictionary *dic in responseObject) {
            _brandesarray = [Brandesarray modelWithDic:dic];
            [_falseIndexArray addObject:[_brandesarray.title substringToIndex:1]];
            [_brandArray addObject:_brandesarray];
            
        }
        for (NSString *str in _falseIndexArray) {
            if (![_indexArray containsObject:str]) {
                [_indexArray  addObject:str];
            }
        }
        _brandMutabDictionary = [NSMutableDictionary dictionary];
        _brandLinkShareDictionary = [NSMutableDictionary dictionary];
        for (Brandesarray *esarray  in _brandArray) {
            if (![_brandMutabDictionary objectForKey:[esarray.title substringToIndex:1]]) {
                NSMutableArray *array = [NSMutableArray array];
                [array addObject:esarray.cover_thumb_hd];
                [_brandMutabDictionary setObject:array forKey:[esarray.title substringToIndex:1]];
                
                NSMutableArray *linkArray = [NSMutableArray array];
                [linkArray addObject:esarray.link_share];
                [_brandLinkShareDictionary setObject:linkArray forKey:[esarray.title substringToIndex:1]];
            } else {
                NSMutableArray *array = [_brandMutabDictionary objectForKey:[esarray.title substringToIndex:1]];
                [array addObject:esarray.cover_thumb_hd];
                
                
                NSMutableArray *linkArray = [_brandLinkShareDictionary objectForKey:[esarray.title substringToIndex:1]];
                [linkArray addObject:[esarray link_share]];
            }
            NSString *link_share = [esarray link_share];
            [[self link_shareArray]addObject:link_share];
            
        }
        [self.brandCollection reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark -----------集合视图item的点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    BrandDetailViewController *brandDetailVC = [BrandDetailViewController new];
    
    [self.navigationController pushViewController:brandDetailVC animated:YES];
    
    NSInteger row = indexPath.row;
    NSInteger section = indexPath.section;
    
    
    NSString *key = [[self indexArray] objectAtIndex:section];
    
    NSArray *linkArray = [_brandLinkShareDictionary objectForKey:key];
    
    NSString *link_share = [linkArray objectAtIndex:row];
    
    NSInteger count = [_brandArray count];
    
    for (int i = 0; i < count; i++) {
        if (_link_shareArray[i] == link_share) {
            [brandDetailVC setRowValue:i];
        }
    }
    [brandDetailVC setLink_shareArray:_link_shareArray];
    
}


//#pragma mark -----more网络请求
//- (void)moreNetworkGet
//{
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    NSString *requestURLString = @"http://watch-cdn.idailywatch.com/app/watch/honored?ver=iphone&app_ver=15&lang=zh-Hans-CN";
//    
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.requestSerializer.timeoutInterval = 0;
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    [manager GET:requestURLString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSDictionary *dic = [NSDictionary dictionary];
//        dic = responseObject;
//        _moreESRootClass = [MoreESRootClass modelWithDic:dic];
//        
//        [self.brandCollection reloadData];
//        
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//       
//    }];
//}

#pragma mark ------------点击方法
- (void)wikipedClicked
{
    WikipediaViewController *wikipedVC = [WikipediaViewController new];
    
    [self.navigationController pushViewController:wikipedVC animated:YES];
    wikipedVC.wikipedArray = _wikipediaesArray;
}



#pragma mark -------腕表百科网络请求
- (void)wikipediaNetwork
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *requestURLString = @"http://watch-cdn.idailywatch.com/api/list/wiki/zh-hans?page=1&ver=iphone&app_ver=15";
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 60;
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager GET:requestURLString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        _wikipediaesArray = [NSMutableArray array];
        for (NSDictionary *dic in responseObject) {
            Wikipediaesarray *wikipediaesarray = [Wikipediaesarray modelWithDic:dic];
            [_wikipediaesArray addObject:wikipediaesarray];
        }

        [self.brandCollection reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",task.currentRequest);
        NSLog(@"请求失败%@",error);
    }];

}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
